package com.hibernate;

import com.entity.Employee;
import com.entity.Timekeeper;
import com.utils.DataUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PersistTransientDemo {

    private static DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    private static Timekeeper persist_Transient(Session session, Employee emp){
        Timekeeper tk1 = new Timekeeper();

        tk1.setEmployee(emp);
        tk1.setInOut(Timekeeper.IN);
        tk1.setDateTime(new Date());

        System.out.println("tk1 Persistent?" + session.contains(tk1));

        System.out.println("call persist(tk1)");

        session.persist(tk1);

        System.out.println("tk1.getTimeKeepId" + tk1.getTimekeeperId());

        // Now 'tk1' is Persistent object.
        // But no action with DB.
        // ==> true
        System.out.println("persisten?"+session.contains(tk1));

        System.out.println("call flush");

        // Flush data to DB.
        // Hibernate execute insert state
        session.flush();

        String timekeeperId = tk1.getTimekeeperId();
        System.out.println("- timekeeperId = " + timekeeperId);
        System.out.println("- inOut = " + tk1.getInOut());
        System.out.println("- dateTime = " + df.format(tk1.getDateTime()));
        System.out.println();
        return tk1;


    }

    public static void main(String[] args) {
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();

        Employee emp = null;
        try {
            session.getTransaction().begin();

            emp = DataUtils.findEmployee(session, "E7499");

            persist_Transient(session, emp);

            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
            session.getTransaction().rollback();
        }
    }
}
